package zhklappoint.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import zhklappoint.annotation.IgnoreAuth;
import zhklappoint.annotation.LoginUser;
import zhklappoint.entity.WXUser;
import zhklappoint.entity.vo.FullUserInfo;
import zhklappoint.entity.vo.UserInfo;
import zhklappoint.enums.ENUM_SUCESS;
import zhklappoint.enums.ENUM_SYSTEM;
import zhklappoint.service.TokenService;
import zhklappoint.service.WXUserService;
import zhklappoint.util.ApiUserUtils;
import zhklappoint.util.CharUtil;
import zhklappoint.util.CommonUtil;
import zhklappoint.util.ResponseBean;
import zhklappoint.util.Tools;

@Controller
@CrossOrigin
@RequestMapping(value="/uni/api",produces = "text/html;charset=UTF-8")
public class LoginController {

	
	@Autowired
	private WXUserService wxUserService;
	@Autowired
	private TokenService tokenService;
	
	/**
	 * 预约系统登录
	 */
	@IgnoreAuth
	@RequestMapping(value="/loginAppoint", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String appointLogin(HttpServletRequest request) {//,String code,Integer type,String userInfo
		JSONObject jsonParam = this.getJsonRequest(request);
		FullUserInfo fullUserInfo = null;
		String code = "";
		String type="4";
		if (!ObjectUtils.isEmpty(jsonParam.getString("code"))) {
			code = jsonParam.getString("code");
		}
		if (null != jsonParam.get("userInfo")) {
			fullUserInfo = jsonParam.getObject("userInfo", FullUserInfo.class);
		}
		if (null == fullUserInfo) {
			return ResponseBean.of(2,ENUM_SUCESS.FAILED.value,"登录失败");
		}
		if (!ObjectUtils.isEmpty(jsonParam.getString("type"))) {
			type = jsonParam.getString("type");
		}

		UserInfo userInfo = fullUserInfo.getUserInfo();
		//获取openid
		String requestUrl = "";
		if(!ObjectUtils.isEmpty(type)&&Integer.valueOf(type)==ENUM_SYSTEM.APPOINT.value) {
			requestUrl = ApiUserUtils.getAppointAccess(code);//通过自定义工具类组合出小程序需要的登录凭证 code
		}else if(!ObjectUtils.isEmpty(type)&&Integer.valueOf(type)==ENUM_SYSTEM.APPOINTADMIN.value) {
			requestUrl = ApiUserUtils.getAppointAdminAccess(code);//通过自定义工具类组合出小程序需要的登录凭证 code
		}else {
			return ResponseBean.of(1,ENUM_SUCESS.FAILED.value,"登录来源有误");
		}
		JSONObject sessionData = CommonUtil.httpsRequest(requestUrl, "GET", null);
//		System.out.println("sessionData"+sessionData);
		if (null == sessionData || ObjectUtils.isEmpty(sessionData.getString("openid"))) {
			return ResponseBean.of(3,ENUM_SUCESS.FAILED.value,"登录失败");
		}
		//验证用户信息完整性
		String sha1 = CommonUtil.getSha1(fullUserInfo.getRawData() + sessionData.getString("session_key"));
//		System.out.println(fullUserInfo.getSignature()+"-----"+sha1);
		if (!fullUserInfo.getSignature().equals(sha1)) {
			return ResponseBean.of(1,ENUM_SUCESS.FAILED.value,"登录失败");
		}
		Date nowTime = new Date();
		WXUser userVo = wxUserService.findByWeixinOpenid(sessionData.getString("openid").toString());
		if (ObjectUtils.isEmpty(userVo)) {
			userVo = new WXUser();
			userVo.setUsername("微信用户" + CharUtil.getRandomString(12));
			userVo.setPassword(sessionData.getString("openid"));
			userVo.setRegisterTime(nowTime);
//			userVo.setRegisterIp(this.getClientIp());
			userVo.setRegisterIp(Tools.getIP(request));
			userVo.setLastLoginIp(Tools.getIP(request));
			userVo.setLastLoginTime(userVo.getRegisterTime());
			userVo.setWeixinOpenid(sessionData.getString("openid"));
			userVo.setAvatar(userInfo.getAvatarUrl());
			//性别 0：未知、1：男、2：女
			userVo.setGender(userInfo.getGender());
			userVo.setNickname(userInfo.getNickName());
			if(!ObjectUtils.isEmpty(type)&&Integer.valueOf(type)==ENUM_SYSTEM.APPOINT.value) {
				userVo.setIntoWay(ENUM_SYSTEM.APPOINT.value);
			}else if(!ObjectUtils.isEmpty(type)&&Integer.valueOf(type)==ENUM_SYSTEM.APPOINTADMIN.value) {
				userVo.setIntoWay(ENUM_SYSTEM.APPOINTADMIN.value);
			}else {
				return ResponseBean.of(1,ENUM_SUCESS.FAILED.value,"登录来源有误");
			}
//			userVo.setShopCode(shopCode);
			wxUserService.save(userVo);
		} else {
			userVo.setLastLoginIp(Tools.getIP(request));
			userVo.setLastLoginTime(nowTime);
			wxUserService.save(userVo);
		}

		Map<String, Object> tokenMap = tokenService.createToken(userVo.getId(),0);
		String token = tokenMap.get("token").toString();

		if (ObjectUtils.isEmpty(userInfo) || ObjectUtils.isEmpty(token)) {
			return ResponseBean.of(4,ENUM_SUCESS.FAILED.value,"登录失败");
		}
		Map<String, Object> resultObj = new HashMap<String, Object>();
		resultObj.put("token", token);
		resultObj.put("userInfo", userInfo);
		resultObj.put("phone", userVo.getMobile());
		return ResponseBean.of(resultObj,ENUM_SUCESS.SUCESS.value,"登录成功");
	}
	

	@RequestMapping(value="/checkIsBusiness", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String checkIsBusiness(@LoginUser WXUser user) {
		if(ObjectUtils.isEmpty(user.getMobile())) {
			return ResponseBean.of(false,ENUM_SUCESS.FAILED.value,"请验证手机");
		}
		return ResponseBean.of(true,ENUM_SUCESS.SUCESS.value,"登录成功");
	}
	
	public JSONObject getJsonRequest(HttpServletRequest request) {
		JSONObject result = null;
		StringBuilder sb = new StringBuilder();
		try (BufferedReader reader = request.getReader();) {
			char[] buff = new char[1024];
			int len;
			while ((len = reader.read(buff)) != -1) {
				sb.append(buff, 0, len);
			}
			result = JSONObject.parseObject(sb.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}
